package com.tbh.security6.controller;


import com.tbh.security6.entity.SysUser;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/security")
public class SecurityController {


    @GetMapping("secured")
    @Secured({"ROLE_ADMINS"})
    public String secured() {
        return "secured";
    }

    @GetMapping("preauthorize")
//    @PreAuthorize("hasAnyRole()")
//    @PreAuthorize("hasPermission()")
    @PreAuthorize("hasAnyAuthority('admins')")
    public String preauthorize() {
        System.out.println("@PreAuthorize(\"hasAnyRole('ROLE_ADMINS')\") 是方法执行完之后执行");
        return "preauthorize";
    }

    @GetMapping("postauthorize")
    @PostAuthorize("hasAnyRole('ROLE_ADMINSS')")
    public String postauthorize() {
        System.out.println("@PostAuthorize(\"hasAnyRole('ROLE_ADMINSS')\") 是方法执行完之后执行");
        return "postauthorize";
    }

    @GetMapping("prefilter/{param}")
    @Secured({"ROLE_ADMINS"})
    @PreFilter(filterTarget = "param", value = "filterObject%2 == 0")
    public SysUser prefilter(@PathVariable Integer param) {
        SysUser sysUser = new SysUser();
        sysUser.setId(param);
        return sysUser;
    }

    @GetMapping("postfilter")
    @Secured({"ROLE_ADMINS"})
    // filterObject是内置的对象，可以读取到目标属性
    @PostFilter("filterObject.id != 1")
    @ResponseBody
    public List<SysUser> postfilter() {
        List<SysUser> list = new ArrayList<SysUser>();
        SysUser sysUser = new SysUser();
        sysUser.setId(1);
        list.add(sysUser);
        SysUser sysUser2 = new SysUser();
        sysUser2.setId(2);
        list.add(sysUser2);

        return filter(list);
    }

    @PreFilter(filterTarget = "list", value = "filterObject.id%2 == 0")
    public List<SysUser> filter(List<SysUser> list) {
        System.out.println(list);
        return list;
    }
}
